from rest_framework import serializers
from Dify.models.batch import *
from django.utils import timezone


# 商品批次表
class GoodsBatchSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsBatch
        fields = '__all__'
        extra_kwargs = {
            'admin_id': {'write_only': True},
            'createtime': {'write_only': True},
            'updatetime': {'write_only': True},
        }

    def validate(self, data):
        # 验证生产日期和保质期的逻辑关系
        if data.get('manufacture') and data.get('guarantee'):
            manufacture_date = timezone.datetime.fromtimestamp(data['manufacture'])
            validity_date = manufacture_date + timezone.timedelta(days=data['guarantee'])
            if 'validity' in data and data['validity']:
                if int(validity_date.timestamp()) != data['validity']:
                    raise serializers.ValidationError({
                        'validity': '有效期与生产日期+保质期不匹配'
                    })

        # 批次号不能重复
        batch_name = data.get('batch_name')
        if batch_name:
            queryset = FaKuyouGoodsBatch.objects.filter(batch_name=batch_name)
            if self.instance:
                queryset = queryset.exclude(pk=self.instance.id)
            if queryset.exists():
                raise serializers.ValidationError({
                    'batch_name': '该批次号已存在'
                })

        return data


# 商品退货批次详情表
class FaKuyouGoodsBatchExchangeInfoSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    type_display = serializers.CharField(source='get_type_display', read_only=True)

    class Meta:
        model = FaKuyouGoodsBatchExchangeInfo
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }


# 商品销售批次详情表
class GoodsBatchSaleInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsBatchSaleInfo
        fields = '__all__'

    def validate(self, data):
        # 验证库存不能为负数
        if 'stock' in data and float(data['stock']) < 0:
            raise serializers.ValidationError({
                'stock': '库存数量不能为负数'
            })

        # 验证期初数量不能为负数
        if 'number' in data and data['number'] is not None and float(data['number']) < 0:
            raise serializers.ValidationError({
                'number': '期初数量不能为负数'
            })

        # 验证生产日期和保质期的逻辑关系
        if data.get('manufacture') and data.get('guarantee'):
            manufacture_date = timezone.datetime.fromtimestamp(data['manufacture'])
            validity_date = manufacture_date + timezone.timedelta(days=data['guarantee'])
            if 'validity' in data and data['validity']:
                if int(validity_date.timestamp()) != data['validity']:
                    raise serializers.ValidationError({
                        'validity': '有效期与生产日期+保质期不匹配'
                    })

        return data


# 批次跟踪表
class FaKuyouGoodsBatchLogSerializer(serializers.ModelSerializer):
    business_type_display = serializers.CharField(source='get_business_type_display', read_only=True)

    class Meta:
        model = FaKuyouGoodsBatchLog
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }


# 商品库存批次跟踪表
class FaKuyouGoodsBatchStockSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = FaKuyouGoodsBatchStock
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }
